package com.zdsoft.blp.zongbuju.shouye.taoshihui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zdsoft.blp.R;
import com.zdsoft.blp.gongyong.API.API;
import com.zdsoft.blp.gongyong.fanhui.FanHuiView;
import com.zdsoft.blp.gongyong.net.BaseActivity;
import com.zdsoft.blp.gongyong.net.Net;
import com.zdsoft.blp.gongyong.net.NetCallback;
import com.zdsoft.blp.zongbuju.shouye.taoshihui.entity.Address;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

/**
 * Created by pc on 2016/9/2.
 */
public class ZhiFuActivity extends BaseActivity implements NetCallback,View.OnClickListener{
    private FanHuiView fh;
    private RelativeLayout rl_xuanzdz,rl_internet,rl_huoDao,rl_xianXia,rl_address;
    private TextView tv_goodsName,tv_price,tv_number,tv_zPrice,tv_name,tv_phone,tv_address,tv_pay;
    private ImageView iv_internet,iv_huoDao,iv_xianXia,iv_songhuo;
    private String zffsCode = "wszf";
    private String addressId = "";
    private static final int HUOQUZHIFIPEISONGTYPE =1;
    private static final int HUOQUADDRESS =2;
    private static final int XUANZEADDRESS =3;
    private static final int SAVEPAYWAY =4;
    private PopupWindow popupWindow;
    private boolean isFirstQingQ =true;

    //支付宝用到的
    // 商户PID
    public static final String PARTNER = "2088021821653648";
    // 商户收款账号
    public static final String SELLER = "505886138@qq.com";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICXQIBAAKBgQDykTgVi//39MaPKq3VqUsgbryo8i+zu44Hr8qhSKdXqrLHL0cyh/qGwvTGHvYxxp5Jz0KXssU32HkZz49JBntEIeJtUsfv69HOBhEORV/1F5g5J7KUgfFKBi9q8xXl/I5gtVrv4eqgIlitjzyj6Bba3vanWzwZXTGSYOb2UEr5yQIDAQABAoGAOF+VmDRcPcUubFFv6wsYQaZaxCzc9zlsjc7GGeunsJEkUXRkaJL/n1gpyO2jK/hMCz1W7aiHey4dHumFFGSkOsKEU7FLss+pzH05FqZTHdp1IdnYPopce+WIHn3DIwSD+Y3ePQgW572ZRoaMk9EcdOJUTp7bDNovXfqCBu/pd4ECQQD/XRriEckVJZCUaoXGDnrMleVrGI5eWep6DdCvxC0w5CuzR3Dytj+xoQwf74/uh9N64eTMGsT1bkHMfC78aGyxAkEA8yvziGdsDA+fQ9+DjIQvFcu2mcqCEdvPdCEhr4R36AlfLnxlKZiWfF1nc2I3U7HJm+WMMynORmEAxz5unfNEmQJBANV1/6XgViWOLChUTxS7P91Ko+b9NO0b3ow+hiaXJ2uKIBmR65GH1QBn7hm4CKnM8nPy5m3TJrc+flQvrpshs1ECQQCHS0nY96nO4BY9nitDz/uehdQXputNYl3+/7wNOoe4Kxaw93cVeJcppJI9SUT9JOrF+SZTBQyGbcwQDvVeng3pAkBY5NTSJ6f/zqlNPD2Uy4Q+T/HGx2QrfbkVVhk/Zu2ObZXvswRNTBkus6fZpMhrcmkevlqn/ksFN7KO2L3rzdgm";
    // 支付宝公钥
    public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDykTgVi//39MaPKq3VqUsgbryo8i+zu44Hr8qhSKdXqrLHL0cyh/qGwvTGHvYxxp5Jz0KXssU32HkZz49JBntEIeJtUsfv69HOBhEORV/1F5g5J7KUgfFKBi9q8xXl/I5gtVrv4eqgIlitjzyj6Bba3vanWzwZXTGSYOb2UEr5yQIDAQAB";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    @Override
    protected void init() {
        setContentView(R.layout.tsh_zhifu);
        fh = find(R.id.fh);
        rl_xuanzdz = find(R.id.rl_xuanzdz);
        tv_goodsName = find(R.id.tv_goodsName);
        tv_price = find(R.id.tv_price);
        tv_number = find(R.id.tv_number);
        tv_zPrice = find(R.id.tv_zPrice);
        rl_internet = find(R.id.rl_internet);
        rl_huoDao = find(R.id.rl_huoDao);
        rl_xianXia = find(R.id.rl_xianXia);
        iv_internet = find(R.id.iv_internet);
        iv_huoDao = find(R.id.iv_huoDao);
        rl_address = find(R.id.rl_address);
        iv_xianXia = find(R.id.iv_xianXia);
        tv_name = find(R.id.tv_name);
        tv_phone = find(R.id.tv_phone);
        tv_address = find(R.id.tv_address);
        iv_songhuo = find(R.id.iv_songhuo);
        tv_pay = find(R.id.tv_pay);

        fh.getTv_title().setText("确认支付");
        tv_goodsName.setText(getIntent().getStringExtra("goodsName"));
        tv_price.setText("¥"+getIntent().getStringExtra("price"));
        tv_number.setText("*"+getIntent().getStringExtra("number"));
        tv_zPrice.setText("¥"+getIntent().getStringExtra("zPrice"));
        iv_internet.setImageResource(R.drawable.wszf);
        orderInfo();
        getAddress();

        rl_internet.setOnClickListener(this);
        rl_huoDao.setOnClickListener(this);
        rl_xianXia.setOnClickListener(this);
        rl_xuanzdz.setOnClickListener(this);
        rl_address.setOnClickListener(this);
        tv_pay.setOnClickListener(this);
    }

    private void orderInfo() {
        Net net = new Net();
        net.url = API.GOODS_URL;
        net.nameSpace = API.GOODS_NAMESPACE;
        net.methodName = API.GOODSPSFS;
        Map<String, Object> map = new HashMap<>();
        map.put("id", getIntent().getStringExtra("goodsId"));
        net.parms = map;
        net.code = HUOQUZHIFIPEISONGTYPE;
        getServer(net, ZhiFuActivity.this);
    }

    public void getAddress() {
        SharedPreferences sp = ZhiFuActivity.this.getSharedPreferences("info", Context.MODE_PRIVATE);
        String userId = sp.getString("userId", "");
        Net net = new Net();
        net.url = API.ADDRESS_URL;
        net.nameSpace = API.ADDRESS_NAMESPACE;
        net.methodName = API.ADDRESSLIST;
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        net.parms = map;
        net.code = HUOQUADDRESS;
        getServer(net, ZhiFuActivity.this);
    }

    @Override
    public void onResponse(boolean flag, int code, String res) {
        if(flag&&code == HUOQUZHIFIPEISONGTYPE){
            try {
                JSONObject object = new JSONObject(res);
                JSONArray array =  object.getJSONArray("zffs");
                for(int i = 0;i<array.length();i++){
                    JSONObject zffsObject = array.getJSONObject(i);
                    if("wszf".equals(zffsObject.getString("code"))){
                        rl_internet.setVisibility(View.VISIBLE);
                    }
                    if("hdfk".equals(zffsObject.getString("code"))){
                        rl_huoDao.setVisibility(View.VISIBLE);
                    }
                    if("xxzf".equals(zffsObject.getString("code"))){
                        rl_xianXia.setVisibility(View.VISIBLE);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if(flag&&code==HUOQUADDRESS){
            try {
                JSONArray array = new JSONArray(res);
                if(array.length()>0){
                    for(int i = 0;i<array.length();i++){
                        JSONObject address = array.getJSONObject(i);
                        if("Y".equals(address.getString("moren"))){
                            rl_address.setVisibility(View.VISIBLE);
                            tv_name.setText(address.getString("xingming"));
                            tv_phone.setText(address.getString("dianhua"));
                            tv_address.setText(address.getString("xiangxi"));
                            iv_songhuo.setImageResource(R.drawable.wszf);
                            addressId = address.getString("id");
                        }
                    }
                }else {
                    getPopupWindow();
                    backgroundAlpha();
                    // 这里是位置显示方式,在屏幕的上侧
                    popupWindow.showAtLocation(tv_goodsName,Gravity.CENTER,0,0);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if(flag&&code==SAVEPAYWAY){
            try {
                JSONObject object = new JSONObject(res);
                Toast.makeText(getApplicationContext(),object.getString("msg"),Toast.LENGTH_SHORT).show();
                if(object.getBoolean("result")){
                    ZhiFuActivity.this.finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_internet:
                selected(iv_internet);
                zffsCode = "wszf";
                break;
            case R.id.rl_huoDao:
                selected(iv_huoDao);
                zffsCode = "hdfk";
                break;
            case R.id.rl_xianXia:
                selected(iv_xianXia);
                zffsCode = "xxzf";
                break;
            case R.id.rl_xuanzdz:
                getAddress();
                break;
            case R.id.rl_address:
                Intent intent = new Intent(getApplicationContext(),XuanZeAddressActivity.class);
                intent.putExtra("addressId",addressId);
                startActivityForResult(intent,XUANZEADDRESS);
                break;
            case R.id.tv_pay:
                if("".equals(zffsCode)||zffsCode==null){
                    Toast.makeText(getApplicationContext(),"请选择支付方式",Toast.LENGTH_SHORT).show();
                }else if("".equals(addressId)||addressId==null){
                    Toast.makeText(getApplicationContext(),"请选择配送方式",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(),zffsCode+"___"+addressId,Toast.LENGTH_SHORT).show();
                    if("hdfk".equals(zffsCode)){
                        hdfk();
                    }else if("wszf".equals(zffsCode)){
                        //pay(tv_goodsName.getText().toString(),getIntent().getStringExtra("zPrice"));
                    }else if("xxzf".equals(zffsCode)){
                        xxzf();
                    }
                }
                break;
        }
    }

    private void hdfk() {
        SharedPreferences sp = ZhiFuActivity.this.getSharedPreferences("info", Context.MODE_PRIVATE);
        String userId = sp.getString("userId", "");
        if(!"".equals(userId)){
            Net net = new Net();
            net.url = API.GOODSORDER_URL;
            net.nameSpace = API.GOODSORDER_NAMESPACE;
            net.methodName = API.PAYONDELIVERY;
            Map<String, Object> map = new HashMap<>();
            String orderid = getIntent().getStringExtra("orderId");
            map.put("orderInfoId", orderid.substring(0,orderid.length()-1));
            map.put("userId",userId);
            net.parms = map;
            net.code = SAVEPAYWAY;
            getServer(net, ZhiFuActivity.this);
        }
    }

    private void xxzf() {
        SharedPreferences sp = ZhiFuActivity.this.getSharedPreferences("info", Context.MODE_PRIVATE);
        String userId = sp.getString("userId","");
        if(!"".equals(userId)){
            Net net = new Net();
            net.url = API.GOODSORDER_URL;
            net.nameSpace = API.GOODSORDER_NAMESPACE;
            net.methodName = API.SAVEPAYWAY;
            Map<String, Object> map = new HashMap<>();
            String orderid = getIntent().getStringExtra("orderId");
            map.put("orderInfoId", orderid.substring(0,orderid.length()-1));
            map.put("userId", userId);
            net.parms = map;
            net.code = SAVEPAYWAY;
            getServer(net, ZhiFuActivity.this);
        }
    }

    private void selected(ImageView image){
        iv_internet.setImageResource(R.drawable.xxzf);
        iv_huoDao.setImageResource(R.drawable.xxzf);
        iv_xianXia.setImageResource(R.drawable.xxzf);
        image.setImageResource(R.drawable.wszf);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==XUANZEADDRESS&&resultCode==RESULT_OK){
            Bundle bundle = data.getExtras();
            Address address = (Address) bundle.get("address");
            tv_name.setText(address.getName());
            tv_phone.setText(address.getDianhua());
            tv_address.setText(address.getXiangxi());
            addressId = address.getId();
            isFirstQingQ =false;
        }
    }

    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            return;
        } else {
            initPopuptWindow();
        }
    }

    protected void initPopuptWindow() {
        // TODO Auto-generated method stub
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        View popupWindow_view = getLayoutInflater().inflate(R.layout.tishiaddress, null, false);
        Button bt_queding = (Button) popupWindow_view.findViewById(R.id.bt_queding);
        Button bt_quxiao = (Button) popupWindow_view.findViewById(R.id.bt_quxiao);

        bt_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dissmiss();
                //getAddress();
            }
        });
        bt_queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),SHAddressActivity.class);
                intent.putExtra("isFirst",true);
                startActivity(intent);
                dissmiss();
            }
        });

        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        popupWindow = new PopupWindow(popupWindow_view, 900, 400, true);
        // 设置动画效果
        // popupWindow.setAnimationStyle(R.style.AnimationFade);
        // 点击其他地方消失
        /*popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });*/
    }

    public void backgroundAlpha() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = (float) 0.5; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    public void dismissBackgroundAlpha() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    //让pop消失
    private void dissmiss() {
        popupWindow.dismiss();
        popupWindow = null;
        dismissBackgroundAlpha();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (isFirstQingQ){
            getAddress();
        }
    }

    /*//以下是支付宝用到的
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(ZhiFuActivity.this, "支付成功",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(ZhiFuActivity.this, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(ZhiFuActivity.this, "支付失败",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(ZhiFuActivity.this, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        };
    };

    *//**
     * call alipay sdk pay. 调用SDK支付
     *
     *//*
    public void pay(String title,String zPrice) {
        if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
                || TextUtils.isEmpty(SELLER)) {
            new AlertDialog.Builder(this)
                    .setTitle("警告")
                    .setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialoginterface, int i) {
                                    //
                                    finish();
                                }
                            }).show();
            return;
        }
        // 订单
        //String orderInfo = getOrderInfo(tv_goodsName.getText().toString(), "", tv_zPrice.getText().toString());
        String orderInfo = getOrderInfo(title, "a", zPrice);

        // 对订单做RSA 签名
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ZhiFuActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    *//**
     * check whether the device has authentication alipay account.
     * 查询终端设备是否存在支付宝认证账户
     *
     *//*
    public void check(View v) {
        Runnable checkRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask payTask = new PayTask(ZhiFuActivity.this);
                // 调用查询接口，获取查询结果
                boolean isExist = payTask.checkAccountIfExist();

                Message msg = new Message();
                msg.what = SDK_CHECK_FLAG;
                msg.obj = isExist;
                mHandler.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();

    }

    *//**
     * get the sdk version. 获取SDK版本号
     *
     *//*
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
        Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
    }

    *//**
     * create the order info. 创建订单信息
     *
     *//*
    public String getOrderInfo(String subject, String body, String price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "http://shequ.zhidisoft.cn/mo/goods/goodsPayResult_notify.jsonp"
                + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    *//**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     *
     *//*
    public String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
                Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    *//**
     * sign the order info. 对订单信息进行签名
     *
     * @param content
     *            待签名订单信息
     *//*
    public String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    *//**
     * get the sign type we use. 获取签名方式
     *
     *//*
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }*/
}
